(function() {
	'use strict';
	
	require(['box', 'bootstrapTable', 'bootstrapTableZh', 'form', 'confirm', 'select2'], function(box) {
		
		if(typeof jQuery === 'undefined') {	//检测jquery依赖项
			throw new Error('jquery依赖项未能加载');
		}
		
		if(typeof $.fn.bootstrapTable === 'undefined') {	//检测bootstrapTable依赖项
			throw new Error('bootstrapTable依赖项未能加载');
		}
		
		if(typeof $.fn.form === 'undefined') {
			throw new Error('form依赖项未能加载');
		}
		
		//有全选且点文字可以选中
		$("#checkbox").selectCheck();
		
		var $main = $('#target_list'),	//本页面的最大div
		$table = $('#target_retrieve'),	//jquery包装table对象，使其能够调用扩展后jquery的方法
		$addBtn = $('#target_add'),
		formId = 'target_create_form',
		formid2 = 'target_update_form',
    	selections = [];
		
		//初始化表格
		function initTable() {	//加载内容
	        $table.bootstrapTable({
				width: '90%',
	            columns: [
	                {field: 'state', checkbox: true},
	      			{width: '33%', field: 'targetNameOfImplphase', title: '实施期目标', align: 'center'},
	      			{width: '25%', field: 'projectName', title: '工程名称', align: 'center'},
	      			{width: '25%', field: 'targetAttributeName', title: '项目名称', align: 'center'},
	      			{width: '15%', field: 'crud', title: '操作', align: 'center', events: roleEvents, formatter: operateFormatter}
	      		],
	      		clickToSelect: true,
	      		singleSelect: true,
	      		checkboxHeader: false,
	      		checkbox: true,
	      		onClickRow: function(row, $element, field) {
	      		}
	        });
	        setTimeout(function () {
	            $table.bootstrapTable('resetView');
	        }, 200);
	        
	        $table.on('expand-row.bs.table', function (e, index, row, $detail) {
	        	var detail = detailFormatter(index, row);
	        	$detail.html(detail);
	        });
	        $table.on('all.bs.table', function (e, name, args) {
	            console.log(name, args);
	        });
	    }
		
	    function getIdSelections() {
	        return $.map($table.bootstrapTable('getSelections'), function (row) {
	            return row.id;
	        });
	    }
	    function responseHandler(res) {
	        $.each(res.rows, function (i, row) {
	            row.state = $.inArray(row.id, selections) !== -1;
	        });
	        return res;
	    }
	    function detailFormatter(index, row) {
	        var html = [];
	        $.each(row, function (key, value) {
	            html.push('<p><b>' + key + ':</b> ' + value + '</p>');
	        });
	        return html.join('');
	    }
	    
	    function operateFormatter(value, row, index) {
	        return [
				'<a class="edit" href="javascript:void(0)" title="编辑">',
				'<i class="glyphicon glyphicon-edit"></i>',
				'</a>  ',
				'<a class="remove" href="javascript:void(0)" title="删除">',
				'<i class="glyphicon glyphicon-remove"></i>',
				'</a>  '				
	        ].join('');
	    }
	    window.roleEvents = {
	        'click .remove': function (e, value, row, index) {
	        	$.alert({title: '提示', content: '此数据为基础数据，请慎重'});
	        	/*var name = row.targetName;
	        	var modalObj = box.configModal('target_list'),
	        	modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId, btnSure = modalObj.btnSure;
	        	var modal = $('#' + modalId), 
    			btn_sure = $('#' + btnSure);
	        	$('#' + modalBodyId).html('确定要删除"' + name + '"吗？');
	        	modal.modal({backdrop: "static"});
	        	
	        	//删除目标
	        	btn_sure.unbind("click").bind("click", function() {
	        		btn_sure.attr('disable', true);
	        		$.ajax({
		        		url: "defaultTarget/deleteDefaultTarget.service",
		        		type: "post",
		        		data: {id: row.id},
		        		success: function(data) {
		        			if(data && data.success) {
		        				getTargets();
		        				modal.modal("hide");
		        			} else {
		        				var modalObj = box.tipModal('target_list'),
	    			        	modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
	    			        	var tip_modal = $('#' + modalId);
		        				modal.modal("hide");
		        				$('#' + modalBodyId).html('目标删除失败。。。。');
		        				tip_modal.modal();
				        	}
		        		},
		        		error: function() {},
		        		complete : function() {
		        			btn_sure.attr('disable', false);
		        		}
		        	});
	        	});*/
	        },
	        //修改目标
	        'click .edit': function (e, value, row, index) {
	        	debugger;
	        	var editdata = row;
	        	var modalObj = box.loadBoxUpdateModal('target_list', "修改目标"),
				modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId, btnSure = modalObj.btnSure;
		    	
		    	var updateUrl = "system/getPage.service?path=manage/department/targetUpdate",
	        	_target = modalBodyId, _selector= "#target_update";
	        	orange.loadPage({url: updateUrl, target: _target, selector: _selector, success: function(response){
	        		var modal = $('#' + modalId), 
					btn_sure = $('#' + btnSure);
	        		$('#targetOfImplPhase').find('input[name="targetNameOfImplphase"]').val(editdata.targetNameOfImplphase);
	        		$('#targetOfImplPhase').find('input[name="projectName"]').val(row.projectName);
	        		$('#targetOfImplPhase').find('input[name="targetAttributeName"]').val(row.targetAttributeName);
	    			$('#'+modalId).find('.modal-content').removeClass('small-box');
	    			setValueToReportReference(editdata);
	    			modal.modal({backdrop: "static"});
	    			btn_sure.unbind('click').bind('click', function() {
	    				modal.modal("hide");
						/*var submitData = {};
	    				btn_sure.attr('disable', true);
	    				submitData = $('#'+formid2).form('getFormData', {id:formid2});
	    				$.ajax({
	    					url: "defaultTarget/updateDafaultTargets.service",
	    					type:"post",
	    					data: submitData,
	    					success: function(data) {
	    						var modalObj = box.tipModal('target_list'),
	    			        	modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
	    			        	var tip_modal = $('#' + modalId); 
	    						if(data && data.success) {
	    							getTargets();
			    	    	         modal.modal('hide');
			    	    	         $('#' + modalBodyId).html('目标修改成功!');
			    	    	         tip_modal.modal();
			        			} else {
			        				modal.modal('hide');
	    				        	$('#' + modalBodyId).html('目标修改失败，网络异常。。。。');
			        				tip_modal.modal();
			        			}
	    					},
	    					complete: function() {
	    						btn_sure.attr("disabled", false);
	    					},
	    					error: function() {}
	    				});*/
	    			});
	    			//给实施期目标赋值
	    		    function setValueToReportReference(objData) {
	    		    	//分解实体类
	    				var targetNameOfImplphase = objData.targetNameOfImplphase? objData.targetNameOfImplphase : ""; //实施期目标名称
	    				var targetNameOfImplphaseId = objData.id? objData.id: "";
	    				var projectId = objData.projectId? objData.projectId: "";
	    				var targetAttribute =objData.targetAttribute? objData.targetAttribute: "";		//"目标属性"
	    				var annualTargetDatalist = objData.annualTargetDatalist?objData.annualTargetDatalist: [];	//年度目标数组
	    				var indexdata = objData.indexEntityList? objData.indexEntityList: [];	//指标，包括：实施期、年度
	    		    	
	    				//实施期目标只有一个，直接赋值
	    				$('#referenceValueOfTarget').val(targetNameOfImplphase);
	    				$('#update_project').val(projectId).trigger('change');
	    				$('#update_attribute').val(targetAttribute).trigger('change');
	    		    	
	    		    	//给年度目标赋值
	    				var aunnalTargetDivs = buildAunnalTargetDivs(annualTargetDatalist);
	    		    	$('#annualTargetlist').append(aunnalTargetDivs);
	    		    	
	    		    	//给指标赋值
	    		    	handleIndex(indexdata);
	    		    	
	    				//构造年度目标
	    				function buildAunnalTargetDivs(annualTargetDatalist) {
	    					var len = annualTargetDatalist? annualTargetDatalist.length : 0, i = 0, resultStr = "";
	    					for(i=0; i<len; i++) {
	    						resultStr += '<div class="aunnalTargetBox" data-index="1">'
	    						+ '<label class="lr-4 ">目标' + (i+1) + ':</label>'
	    						+ '<input class= "fill-1" name="annualTargets" value=' + $.trim(annualTargetDatalist[i]['annualTargets']) + '></input>'
	    						+ '</div>' + '\n';
	    					}
	    					
	    					return resultStr;
	    				}
	    				
	    				//构造指标
	    				function handleIndex(indexData) {
	    					//注意需要id，更新时，需要id直接更新
	    					var i = 0, len =indexData? indexData.length : 0, tempObj = null,
    							id = "", firstIndex = "", secondIndex="", thirdIndex="",
    							indexValue = "", targetType = "", referValue = "",
    							outerdivClsIndex = "", //需要添加一个空格
    							innerDivCls = "", //需要加一个空格
    							filledConstant = "filled", notfilledConstant = "notFilled",
    							outBox = {}, innerBox={}, innerBoxNotFilled = {},
    							$innerBoxNotFilled = {}, innerBoxNotFilledLen = 0, newBox = "";
	    					
	    					for(i = 0; i<len; i++) {
	    						tempObj = indexData[i];
	    						id = tempObj['id'];
	    						firstIndex = tempObj['firstIndex'];
	    						secondIndex = tempObj['secondIndex'];
	    						thirdIndex = tempObj['thirdIndex'];
	    						indexValue = tempObj['indexValue'];
	    						targetType = tempObj['targetType'];
	    						referValue = tempObj['referValue'];
	    						
	    						outerdivClsIndex = targetType + "_" + firstIndex + '_' + secondIndex;
	    						innerDivCls = 'ac_box' + notfilledConstant;
	    						
	    						outBox= $('.targetBox.' + outerdivClsIndex);
	    						innerBox = outBox.children();
	    						
	    						innerBoxNotFilled = outBox.find('.ac_box.' + notfilledConstant);
	    						$innerBoxNotFilled = $(innerBoxNotFilled);
	    						innerBoxNotFilledLen = $innerBoxNotFilled.length;
	    							
	    						if(innerBoxNotFilledLen == 0) {
	    							//构造div
	    							newBox = '<div class="ac_box filled" data-index="' + parseInt(innerBoxNotFilledLen + 1) + '">'
	    									+'<input name="id" type="hidden" value="' + id + '"></input>'
	    					       		   	+ '<label class="lr-4 span-add">指标' + parseInt(innerBoxNotFilledLen + 1) + ':</label>'
	    					       		   	+ '<input class= "fill-4-1" name="' + thirdIndex + '"></input>'
	    					       		   	+ '<label class="lr-4 span-add">参考值</label>'
	    					       		   	+ '<input class= "fill-4-1" name="referValue"></input>'
	    					       		   	+ '</div>';
	    							//添加一个新的div
	    							outBox.append(newBox);
	    						} else {
	    							//有notFilled的div，那就直接插入值
	    							$innerBoxNotFilled.find('input[name="thirdIndex"]').val(thirdIndex);
	    							$innerBoxNotFilled.find('input[name="id"]').val(id);
	    							$innerBoxNotFilled.find('input[name="referValue"]').val(referValue);
	    							$innerBoxNotFilled.removeClass(notfilledConstant).addClass(filledConstant);
	    						} 
	    					}
	    				}
	    		    }
	        	}});
	        }
	    };
	    
	    $addBtn.click(function () {
	    	$.alert({title: '提示', content: '整体目标为基础数据，基础数据已经建立'});
	    	/*var modalObj = box.loadBoxCreateModal('target_list', "创建目标"),
			modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId, btnSure = modalObj.btnSure;
	    	var createUrl = "system/getPage.service?path=manage/department/targetCreate",
        	_target = modalBodyId, _selector= "#target_create";
        	orange.loadPage({url: createUrl, target: _target, selector: _selector, success: function(response){
        		var modal = $('#' + modalId), 
					btn_sure = $('#' + btnSure);
        		$('#'+modalId).find('.modal-content').removeClass('small-box');
				modal.modal({backdrop: "static"});
				btn_sure.unbind('click').bind('click', function(btn) {
					btn_sure.attr("disabled", true);
					var jsonData = $('#'+formId).form('getArrayForm', {id:formId});
						jsonData['targetAttribute'] = $('#create_attribute').val();
						jsonData['creater'] = orange.getAppContext('USER')['username'];
					$.ajax({
    					url: "defaultTarget/createDefaultTarget.service",
    					type:"post",
    					dataType: 'json',
    					data: JSON.stringify(jsonData),
    					contentType : 'application/json;charset=utf-8',
    					success : function(data) {
    						var modalObj = box.tipModal('target_list'),
    			        	modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
    			        	var tip_modal = $('#' + modalId);  
    						if(data && data.success) {
    							getTargets();
    							$table.bootstrapTable('prepend', data.data);
        	    	            modal.modal('hide');
		        			} else {
		        				modal.modal('hide');
    				        	$('#' + modalBodyId).html('目标添加失败。。。');
		        				tip_modal.modal();
		        			}
    					},
    					error: function() {},
    					complete: function() {
    						btn_sure.attr("disabled", false);
    					}
    				});
				});
	    	}});*/
	    });
	    
		 function getTargets() {
			 $.ajax({
				url: 'report/retrieveReportForDOPAF2.service',
				type: 'get',
				success: function(data) {
					if(data && data.success) {
						$table.bootstrapTable('load', data.data[0].targetPhaseList);
					}else if(data && data.success == false) {
						alert(data.errorMsg);
					} else {
						alert('false');
					}						
				}
			});
		 }
		 initTable();
		 getTargets();
	});
})();